package com.panicstyle.Gongdong;

import java.util.regex.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HttpContext;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class BoardActivity extends ListActivity implements Runnable {
	TextView selection;
    private ProgressDialog pd;
	
	protected String boardTitle;
	protected String boardCode;
	protected HttpClient httpClient;
	protected HttpContext httpContext;
    List<HashMap<String, String>> arrayItems;

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Bitmap mIcon1;
        private Bitmap mIcon2;
        private List<HashMap<String, String>> arrayItems;

        public EfficientAdapter(Context context, List<HashMap<String, String>> data) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            // Icons bound to the rows.
            mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_new);
            mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_none);
            
            arrayItems = data;
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return arrayItems.size() ;
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**	
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_boardview, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }
            HashMap<String, String> item = new HashMap<String, String>();
            String title = null;
            String isNew = null;
            item = (HashMap<String, String>)arrayItems.get(position);
            title = (String)item.get("title");
            isNew = (String)item.get("isNew");
            // Bind the data efficiently with the holder.
            holder.title.setText(title);
            if (isNew == "1") {
            	holder.icon.setImageBitmap(mIcon1);
            } else {
            	holder.icon.setImageBitmap(mIcon2);
            }

            return convertView; 
        }
        
        static class ViewHolder {
            TextView title;
            ImageView icon;
        }
    }
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        
        intenter();

        pd = ProgressDialog.show(this, "", "로딩중입니다. 잠시만 기다리십시오...", true,
                false);

        Thread thread = new Thread(this);
        thread.start();

        return;
    }

    public void run() {
    	LoadData(BoardActivity.this);
    	handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		pd.dismiss();
            setListAdapter(new EfficientAdapter(BoardActivity.this, arrayItems));

    	}
    };        

    public void intenter() {
//    	Intent intent = getIntent();  // 값을 가져오는 인텐트 객체생성
    	Bundle extras = getIntent().getExtras();
    	// 가져온 값을 set해주는 부분
    	
    	boardTitle = extras.getString("BOARD_TITLE").toString();
    	boardCode = extras.getString("BOARD_CODE").toString();
    }

    private void LoadData(Context context) {
        
        HttpClient httpClient;
    	HttpContext httpContext;
    	CookieStore cookieStore;
        
        GongdongApplication app = (GongdongApplication)getApplication();
        httpClient = app.httpClient;
        httpContext = app.httpContext;
        cookieStore = app.cookieStore;
        
		arrayItems = getData(httpClient, httpContext);

    }
    
    protected List<HashMap<String, String>> getData(HttpClient httpClient, HttpContext httpContext) {		
		
		String url = "http://cafe.gongdong.or.kr/cafe.php?code=" + boardCode;
		HttpRequest httpRequest = new HttpRequest();

		String result = httpRequest.requestGet(httpClient, httpContext, url);
        
        if (result.indexOf("<select name=\"link_my_cafe") >= 0) {
        	System.out.println("indexOf is true");
        } else {
        	System.out.println("indexOf is false");
        }
        
        // 각 항목 찾기
        HashMap<String, String> item;
        List<HashMap<String, String>> arrayItems = new ArrayList<HashMap<String, String>>();

        Pattern p = Pattern.compile("(<li id=\"cafe_sub_menu)(.|\\n)*?(</li>)", Pattern.CASE_INSENSITIVE); 
        Matcher m = p.matcher(result);
        while (m.find()) { // Find each match in turn; String can't do this.     
            item = new HashMap<String, String>();
            String matchstr = m.group(0);
            
            if (matchstr.indexOf("cafe_sub_menu_line") >= 0) {
            	continue;
            } else if (matchstr.indexOf("cafe_sub_menu_title") >= 0) {
            	item.put("type", "1");
            } else if (matchstr.indexOf("cafe_sub_menu_link") >= 0) {
            	item.put("type", "2");
            } else {
            	item.put("type", "0");
            }
            
            // link	
	        Pattern p2 = Pattern.compile("(?<=<a href=\\\")(.|\\n)*?(?=\\\")", Pattern.CASE_INSENSITIVE); 
	        Matcher m2 = p2.matcher(matchstr);
	        if (m2.find()) { // Find each match in turn; String can't do this.     
	//        	items.add(m.group(0)); // Access a submatch group; String can't do this. }
	            item.put("link", m2.group(0));
	        } else {
	            item.put("link", "");
	        }
	        
	        // title
	        String title = matchstr.replaceAll("<((.|\\n)*?)+>", "");
	        title = title.trim();
      
            item.put("title", title);
            
            // new
            if (matchstr.indexOf("images/new_s.gif") >= 0) {
                item.put("isNew", "1");
            } else {
            	item.put("isNew", "0");
            }
            
            // new
            if (matchstr.indexOf("sort=cal") >= 0) {
                item.put("isCal", "1");
            } else {
            	item.put("isCal", "0");
            }
            
            arrayItems.add( item );
        }
        
        return arrayItems;
    }

    public void onListItemClick(ListView parent, View v, int position, long id) {
        HashMap<String, String> item = new HashMap<String, String>();
        String title = null;
        String link = null;
        item = (HashMap<String, String>)arrayItems.get(position);
        title = (String)item.get("title");
        link = (String)item.get("link");

        Intent intent = new Intent(this, ItemsActivity.class);
        intent.putExtra("ITEMS_TITLE", title);
        intent.putExtra("ITEMS_LINK", link);
        startActivity(intent);    
    }

}